//
//  AppDelegate.m
//  nonghubao
//
//  Created by 王 文彬 on 13-2-22.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

/*
 SUMMARY

 App引导类，主要工作为：
 
 》启动数据库上下文
 》初始化数据库
 》注册推送接口
 》注册观察者，用于监各种界面的切换事件
 》启动LauncherViewController，并由它决定接下来会启动的VC
 
 
 观察者监听的事件类型：
 》DefaultViewController启动调用事件
 》MainViewController启动调用事件
 》DefaultViewController启动完成事件
 》MainViewController启动完成事件

*/

#import "AppDelegate.h"
#import "LaunchViewController.h"
#import "MainViewController.h"
#import "DefaultViewController.h"
#import "DBKit.h"
#import "APService.h"
#import "StatisticsUtil.h"
#import <AudioToolbox/AudioToolbox.h>
#import "DynamicViewController.h"
#import "NoticeViewController.h"
#import "SplashViewController.h"
#import "Option.h"
#import "VersionManager.h"
#import "JMFBase.h"
#import <AddressBook/AddressBook.h>
#import "MoonHTTPRequest.h"
#import "HPopupView.h"
#import "CollageManager.h"
#import "UMSocial.h"

@implementation AppDelegate
{
    MBProgressHUD *HUD;
}

@synthesize socialDelegate = _socialDelegate;


- (id)init
{
    self = [super init];
    if (self) {
        _socialDelegate = [[SocialDelegate alloc] init];
    }
    return self;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    if (iOS7) {
        application.statusBarStyle = UIStatusBarStyleLightContent;
    }
    self.window.backgroundColor = [UIColor whiteColor];

    //umeng组件初始化
    [StatisticsUtil start];
    
    //检查并更新城市数据
    [self regionDataRequest];
    
    [self checkVersion];
    
    ////注册观察者
    NSNotificationCenter* defaultCenter = [NSNotificationCenter defaultCenter];
    //启动DefaultViewController
    [defaultCenter addObserver:self selector:@selector(startDefaultEvent:) name:@"Start_Default" object:nil];
    
    //启动MainViewController
    [defaultCenter addObserver:self selector:@selector(startMainEvent:) name:@"Start_Main" object:nil];
    
    //DefaultViewController启动完成
    [defaultCenter addObserver:self selector:@selector(defaultStartedEvent:) name:@"Default_Started" object:nil];
    
    //MainViewController启动完成
    [defaultCenter addObserver:self selector:@selector(mainStartedEvent:) name:@"Main_Started" object:nil];
    
    //LaunchViewController引导完成
    [defaultCenter addObserver:self selector:@selector(launcherDidFinishEvent:) name:@"Launcher_Finished" object:nil];
    
    //启动splash
    [defaultCenter addObserver:self selector:@selector(startSplashEvent:) name:@"Start_Splash" object:nil];
    
    //初始化数据库，第一次使用数据库时，会自动连接SQLite3
    DBKit* dbkit = [DBKit sharedDBKit];
    [dbkit initDB:DBVersionV2];
    
#warning 测试代码 要去掉
//    Option* option = [[Option alloc] init];
//    option.name = @"sysSplashShown";
//    option.value = @"0";
//    [[DBKit sharedDBKit] save:option];
//-------------
//    
//    NSArray *familyNames = [UIFont familyNames];
//    for( NSString *familyName in familyNames ){
//        printf( "Family: %s \n", [familyName UTF8String] );
//        NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
//        for( NSString *fontName in fontNames ){
//            printf( "\tFont: %s \n", [fontName UTF8String] );
//        }
//    }
    
    
    //检查是否是第一次使用app，如果是则启动splash
    Option* splashOption = [dbkit optionWithName:@"sysSplashShown"];
    
    if ([splashOption.value intValue] == 0) {
        
        _splashViewController = [[SplashViewController alloc] init];
        
        self.window.rootViewController = _splashViewController;
        
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
        
    }else{
        
        
        //启动Launch，Launch会检测用户数据并与服务器做基础数据交换，然后决定启动哪个页面，并通知本类
        _launchViewController = [[LaunchViewController alloc] init];
        _launchViewController.view.tag = 4;

        self.window.rootViewController = _launchViewController;
        
    }
    [self.window makeKeyAndVisible];
    
    // Required
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert)];
    // Required
    [APService setupWithOption:launchOptions];
    
    [defaultCenter addObserver:self selector:@selector(networkDidSetup:) name:kAPNetworkDidSetupNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidClose:) name:kAPNetworkDidCloseNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidRegister:) name:kAPNetworkDidRegisterNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidLogin:) name:kAPNetworkDidLoginNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kAPNetworkDidReceiveMessageNotification object:nil];
    
    [defaultCenter addObserver:self selector:@selector(updateBarBadgeValue:) name:@"Update_Badge" object:nil];
    
    
    //设定appDelegate引导完成，并尝试启动
    //算法：由于AppDelegate和_launcherViewController的执行，是异步的，所以必须双方通过设置各自对应的状态变量，并调用同一个方法，来判断该继续执行哪一步
    _appDelegateDidFinish = YES;
    [self nextStep];
    
    return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    [UMSocialSnsService  applicationDidBecomeActive];
    NSLog(@"TYPESSSSSS: %d", [application enabledRemoteNotificationTypes]);
    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Required
    [APService registerDeviceToken:deviceToken];
//    NSString *d = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
//    d = [d stringByReplacingOccurrencesOfString:@" " withString:@""];
//    NSLog(@"%@", [NSString stringWithFormat:@"%@",d]);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *) error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    [APService handleRemoteNotification:userInfo];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    BOOL isSuc = [WXApi handleOpenURL:url delegate:nil];
    if (isSuc) {
        return isSuc;
    }
    return  [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
#if __QQAPI_ENABLE__
    [QQApiInterface handleOpenURL:url delegate:(id)[QQAPIDemoEntry class]];
#endif
    if (YES == [TencentOAuth CanHandleOpenURL:url])
    {
        return [TencentOAuth HandleOpenURL:url];
    }
    
    BOOL isSuc = [WXApi handleOpenURL:url delegate:nil];
    if (isSuc) {
        return isSuc;
    }
    
    return [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
}

#pragma mark - 私有方法，通知事件

// 启动DefaultViewController
//
- (void)startDefaultEvent:(id)object
{
    if (_mainViewController != nil) {
        [_mainViewController.view removeFromSuperview];
        [_mainViewController removeFromParentViewController];
    }
    
    _defaultViewController = [[DefaultViewController alloc] init];
    _defaultViewController.view.tag = 5;
    
    _defaultNavigationController = [[UINavigationController alloc] initWithRootViewController:_defaultViewController];
    [Helper navigationControllerCommonStyle:_defaultNavigationController];
    
    self.window.rootViewController = _defaultNavigationController;
    [_defaultNavigationController setNavigationBarHidden:YES animated:NO];
    
    
    NSLog(@"\n\n-- DEBUG.AppDelegate.startDefaultEvent --\n\nwindow.subviews.count=%i\n%@\n\n%@", self.window.subviews.count, self.window.subviews, self.window.rootViewController);
}

// 启动MainViewController
//
- (void)startMainEvent:(id)object
{
    if (_launchViewController != nil) {
        [_launchViewController.view removeFromSuperview];
        [_launchViewController removeFromParentViewController];
    }
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    
    _mainViewController = [[MainViewController alloc] init];
    _mainViewController.delegate = self;
    _mainViewController.view.tag = 6;
    self.window.rootViewController = _mainViewController;
    
    NSLog(@"\n\n-- DEBUG.AppDelegate.startMainEvent --\n\nwindow.subviews.count=%i\n%@", self.window.subviews.count, self.window.subviews);
}


// DefaultViewController启动完成
//
- (void)defaultStartedEvent:(id)object
{    
    NSLog(@"\n\n-- DEBUG.AppDelegate.defaultStartedEvent --\n\nwindow.subviews.count=%i\n%@", self.window.subviews.count, self.window.subviews);
}


// MainViewController启动完成
//
- (void)mainStartedEvent:(id)object
{
    //消除
//    [UIView animateWithDuration:0.3f animations:^{
//        _mainViewController.view.alpha = 0.0f;
//    } completion:^(BOOL finished) {
//        [_mainViewController.view removeFromSuperview];
//        [_mainViewController removeFromParentViewController];
//    }];
    
    NSLog(@"\n\n-- DEBUG.AppDelegate.mainStartedEvent --\n\nwindow.subviews.count=%i\n%@", self.window.subviews.count, self.window.subviews);
}


// 接受LauncherViewController引导完成后的通知消息
//
- (void)launcherDidFinishEvent:(NSNotification *)notification
{
    _launcherDidFinish = [notification.object intValue];
    [self nextStep];
}

// 根据_appDelegateDidFinish和_launchDidFinish判定该引导哪一个视图
- (void)nextStep
{
    if (_appDelegateDidFinish == YES && _launcherDidFinish > 0) {
        
        if (_launcherDidFinish == 1) {
            [self startDefaultEvent:nil];
        }
        else if (_launcherDidFinish == 2) {
            [self startMainEvent:nil];
        }
    }
}

#pragma mark -JPush Notification

- (void)networkDidSetup:(NSNotification *)notification {
    
    NSLog(@"已连接");
}

- (void)networkDidClose:(NSNotification *)notification {
    NSLog(@"未连接");
    
}

- (void)networkDidRegister:(NSNotification *)notification {
    
    NSLog(@"已注册");
}

- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录");

}

- (void)networkDidReceiveMessage:(NSNotification *)notification
{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
    //如果APP为非活跃状态，则跳转到消息通知界面
    if ([UIApplication  sharedApplication].applicationState != UIApplicationStateActive) {
        if (_mainViewController) {
            _mainViewController.selectedIndex = 1;
        }
    }
    
    NSDictionary * userInfo = [notification userInfo];

    NSDictionary *extras = [userInfo objectForKey:@"extras"];
    
    //获得extra的值
    _dynamicUnreadCount = [[extras objectForKey:@"noud"] integerValue];
    _noticeUnreadCount = [[extras objectForKey:@"noun"] integerValue];
    
    //设置badge
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Update_Badge" object:nil];
}

- (void)updateBarBadgeValue:(NSNotification *)notification
{
    NSArray *VCs = [_mainViewController viewControllers];
    
    //动态角标
    NSString *dynamicUnreadCount;
    if (_dynamicUnreadCount == 0) {
        
        dynamicUnreadCount = nil;
    
    }else{
        
        dynamicUnreadCount = [NSString stringWithFormat:@"%d",_dynamicUnreadCount];
        
        if (_dynamicUnreadCount > 50) {
            
            dynamicUnreadCount = [NSString stringWithFormat:@"50+"];
        }
    }
    
    [[[VCs objectAtIndex:0] tabBarItem] setBadgeValue:dynamicUnreadCount];
    
    //消息通知角标
    NSString *noticeUnreadCount;
    if (_noticeUnreadCount == 0) {
        
        noticeUnreadCount = nil;
        
    }else{
        
        noticeUnreadCount = [NSString stringWithFormat:@"%d",_noticeUnreadCount];
        
        if (_noticeUnreadCount > 50) {
            
            noticeUnreadCount = [NSString stringWithFormat:@"50+"];
        }
    }
    
    [[[VCs objectAtIndex:1] tabBarItem] setBadgeValue:noticeUnreadCount];
    
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *) viewController {
    
    
    if (_lastIndex == tabBarController.selectedIndex) {
        
        switch (tabBarController.selectedIndex) {
            case 0:
            {
                NSLog(@"你第二次点击圈子商讯");
                //获取到DynamicViewController
                UINavigationController *dynamicNC = (UINavigationController *)viewController;
                
                DynamicViewController *dynamicVC = (DynamicViewController *)dynamicNC.topViewController;
                
                //请求未读消息
                
                [dynamicVC circleMessageRequestWithPageSize:[self pageSizeShouldbBePass:dynamicNC.tabBarItem.badgeValue.integerValue]];
                
                //将未读消息清零
                [dynamicNC.tabBarItem setBadgeValue:nil];
                
            }
                break;
            case 1:
                
            {
                //获取到NoticeViewController
                UINavigationController *noticeNC = (UINavigationController *)viewController;
                
                NoticeViewController *noticeVC = (NoticeViewController *)noticeNC.topViewController;
                
                //请求未读消息
                [noticeVC noticesRequestWithPageSize:[self pageSizeShouldbBePass:noticeNC.tabBarItem.badgeValue.integerValue]];
                
                //将未读消息清零
                [noticeNC.tabBarItem setBadgeValue:nil];
            }
                break;
                
            default:
                break;
        }
    }
    
    _lastIndex = tabBarController.selectedIndex;
    
}

- (NSInteger)pageSizeShouldbBePass:(NSInteger)pageSize
{
    if (pageSize <= 20) {
        
        return 20;
    }
    
    return pageSize;
}

- (void)checkVersion
{
    @autoreleasepool {
        
        NSString *curVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
        NSInteger version = [[curVersion stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
        
        _versionInfo = [VersionManager startVersionChecking:version];
        if (_versionInfo == nil || [_versionInfo[@"status"] intValue] == 0) {  //如果返回空值，说明检查没有通过服务器，或服务器返回了错误
            return;
        }
        
        //这里先和本地存放的最新版本比较，如果一样，那么就不提示更新，否则就要提示
        NSInteger newestVersionLoc = [[NSUserDefaults standardUserDefaults] integerForKey:@"newestVersion"];
        
        if (newestVersionLoc == [_versionInfo[@"sequence"] integerValue]) {
            return;
        }
        
        UpgradeLevel upgradeLevel = [_versionInfo[@"status"] integerValue];
        NSString *title = [NSString stringWithFormat:_L(@"tpl_38"), @""];
        NSString *message = _versionInfo[@"description"];
        _appPath = _versionInfo[@"download"];
        
        HPopupView* popupView = [[HPopupView alloc] init];
        popupView.titleText = title;
        popupView.contentText = message;
        
        if (upgradeLevel == UpgradeOptionalLevel) {
            
            popupView.cancelButtonTitle = _L(@"btn_back_02");
            [popupView addButtonTitlt:_L(@"btn_yes_27")];
            [popupView addButtonTitlt:_L(@"btn_yes_28")];
            
        }
        //强制升级，只显示“立刻升级”
        else if (upgradeLevel == UpgradeRequiredLevel) {
            
            popupView.cancelButtonTitle = _L(@"btn_yes_27");
        }
        
        [popupView setWillShowBlock:^(UIView *view) {
            
            ((UILabel *)view.subviews[1]).textAlignment = UITextAlignmentLeft;
        }];
        [popupView show];
        
        [popupView setButtonClickedBlock:^BOOL(UIView *view, NSInteger buttonIndex) {
            
            BOOL result = true;  //默认消除弹出框
            
            UpgradeLevel upgradeLevel = [_versionInfo[@"status"] integerValue];
            
            if (buttonIndex == 0) {
                
                //非强制升级下，此时为“以后再说”
                if (upgradeLevel == UpgradeOptionalLevel) {
                    
                    //用户点击过以后再说后，那么在当前版本下就不再提示用户升级这次的版本
                    //接着在这次版本更新中，用户每次启动APP时，先读取数据库中的这个版本值，版本请求过后就判断最新的是不是同一个版本，如果是，就不再提示，否则就提示，并且更改这个值
                    [[NSUserDefaults standardUserDefaults] setInteger:[_versionInfo[@"sequence"] integerValue] forKey:@"newestVersion"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
                
                //强制升级下，此时为“立刻去升级”
                else if (upgradeLevel == UpgradeRequiredLevel) {
                    
                    if (_appPath != nil && _appPath.length != 0) {
                        
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_appPath]];
                    }
                    
                    result = false;
                }
            }
            
            //立刻升级
            else if (buttonIndex == 1) {
                
                if (_appPath != nil && _appPath.length != 0) {
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_appPath]];
                }
            }
            
            //稍后提醒
//            else if (buttonIndex == 2) {
//                
//                //30秒后再提醒
//                dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//                dispatch_async(concurrentQueue, ^{
//                    
//                    dispatch_sync(concurrentQueue, ^{
//                        sleep(25.0f);
//                    });
//                    
//                    dispatch_sync(dispatch_get_main_queue(), ^{
//                        
//                        [(HPopupView *)view show];
//                    });
//                });
//            }
            
            return result;
        }];
    }
}

//向服务器请求城市数据
- (void)regionDataRequest
{
    
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_REGION_VERSION_CHECK];
    request.delegate = self;
    [request setValue:[NSNumber numberWithFloat:[[NSUserDefaults standardUserDefaults] floatForKey:@"regionVersion"]] forParameter:@"version"];
    
    [request asynchronous];    
}

//向服务器请求全国大学数据
- (void)collageDataRequest
{
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_SCHOOL_LIST];
    request.delegate = self;
    [request setValue:[NSNumber numberWithFloat:[[NSUserDefaults standardUserDefaults] floatForKey:@"collageVersion"]] forParameter:@"version"];
    [request setSuccessSelector:@selector(collageDataDidReceived:)];
    [request asynchronous];
}

- (void)saveRegionData:(NSDictionary *)data
{
    @autoreleasepool {
        
        [Helper saveRegionDataToPlist:(NSArray *)data[@"list"] withName:@"location_standard.plist" andStandard:YES];    //无空格的
        [Helper saveRegionDataToPlist:(NSArray *)data[@"list"] withName:@"location.plist" andStandard:NO];              //有空格的
        
        [[NSUserDefaults standardUserDefaults] setFloat:[data[@"version"] floatValue] forKey:@"regionVersion"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (void)saveCollageData:(NSDictionary *)data
{
    @autoreleasepool {

        [CollageManager clear];
        
        NSMutableArray *collages = [Helper replaceDictionaryToCollageInResponseData:(NSArray *)data[@"list"]];
        
        //存入数据库
        [CollageManager persistCollages:collages];
        NSLog(@"over");
        [[NSUserDefaults standardUserDefaults] setFloat:[data[@"version"] floatValue] forKey:@"collageVersion"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    
//    if ([_CONFIG_APP_KEY isEqualToString:@"XYSHQ"]) {
        [self collageDataRequest];
//    }
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];

    if (jmf.status == JMStatusSucceed) {

        if (![jmf.data[@"update"] boolValue]) {
            return;
        }
        
        [NSThread detachNewThreadSelector:@selector(saveRegionData:) toTarget:self withObject:jmf.data];
        
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
}

- (void)collageDataDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if (![jmf.data[@"update"] boolValue]) {
            return;
        }
        
        [NSThread detachNewThreadSelector:@selector(saveCollageData:) toTarget:self withObject:jmf.data];
        
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark UIAlertView Delegate

- (void)willPresentAlertView:(UIAlertView *)alertView
{
    if ([alertView.subviews[2] isKindOfClass:[UILabel class]]) {
        
        ((UILabel *)alertView.subviews[2]).textAlignment = NSTextAlignmentLeft;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
//    UpgradeLevel upgradeLevel = [_versionInfo[@"status"] integerValue];
//    
//    if (buttonIndex == 0) {
//        
//        //非强制升级下，此时为“以后再说”
//        if (upgradeLevel == UpgradeOptionalLevel) {
//            
//            //用户点击过以后再说后，那么在当前版本下就不再提示用户升级这次的版本
//            //接着在这次版本更新中，用户每次启动APP时，先读取数据库中的这个版本值，版本请求过后就判断最新的是不是同一个版本，如果是，就不再提示，否则就提示，并且更改这个值
//            [[NSUserDefaults standardUserDefaults] setInteger:[_versionInfo[@"sequence"] integerValue] forKey:@"newestVersion"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//            
//        }
//        
//        //强制升级下，此时为“立刻去升级”
//        else if (upgradeLevel == UpgradeRequiredLevel){
//            
//            if (_appPath != nil && _appPath.length != 0) {
//                
//                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_appPath]];
//            }
//        }
//        
//    }
//    
//    //立刻升级
//    else if (buttonIndex == 1) {
//        
//        if (_appPath != nil && _appPath.length != 0) {
//            
//            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_appPath]];
//        }
//    }
//    
//    //稍后提醒
//    else if (buttonIndex == 2) {
//        
//        //30秒后再提醒
//        dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//        dispatch_async(concurrentQueue, ^{
//            
//            dispatch_sync(concurrentQueue, ^{
//                sleep(25.0f);
//            });
//            
//            dispatch_sync(dispatch_get_main_queue(), ^{
//                [alertView show];
//            });
//        });
//    }
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    UpgradeLevel upgradeLevel = [_versionInfo[@"status"] integerValue];
    
    if (buttonIndex == 0 && upgradeLevel == UpgradeRequiredLevel) {
        [alertView show];
    }
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
	[HUD removeFromSuperview];
	HUD = nil;
}

@end
